package com.ts.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ts.core.entity.Dict;
import com.ts.core.entity.dto.ExcelDictDTO;
import com.ts.core.listener.ExcelDictDTOListener;
import com.ts.core.mapper.DictMapper;
import com.ts.core.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2024-03-24
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    public List<Dict> findByDictCode(String dictcode) {
        //根据dict_code获取这条记录 根据这条记录的id作为parented_id来获取记录列表


        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
        dictQueryWrapper.eq("dict_code",dictcode);
        Dict dict = baseMapper.selectOne(dictQueryWrapper);
        Long id = dict.getId();
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);


        return dictList;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",parentId);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        for(Dict dict:dictList ){
            boolean b = this.hasChildren(dict.getId());
            dict.setHasChildren(b);
        }

        return dictList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        //阿里巴巴的EasyExcel  输入流、 导入数据表对应的DemoData.class、 listener
        EasyExcel.read(inputStream, ExcelDictDTO.class,new ExcelDictDTOListener(baseMapper)).sheet().doRead();
    }

    @Override
    public List listdata() {
        List<Dict> dictList = baseMapper.selectList(null);
        //创建ExcelDictDTO列表 将Dict列表装换成ExcelDTO列表
        ArrayList<ExcelDictDTO> excelDictDTOArrayList=new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            ExcelDictDTO excelDictDTO=new ExcelDictDTO();
            BeanUtils.copyProperties(dict,excelDictDTO);  //对象拷贝
            excelDictDTOArrayList.add(excelDictDTO);

        }

        return excelDictDTOArrayList;
    }

    private boolean hasChildren(Long id){
        QueryWrapper<Dict> dictQueryWrapper=new QueryWrapper<>();
        dictQueryWrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(dictQueryWrapper);
        if(count.intValue()>0){
            return true;
        }
        return  false;
    }

}
